package com.daye.homework.servlet;

import com.daye.homework.factory.AdminServiceFactory;
import com.daye.homework.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AdminLoginServlet" , urlPatterns = "/login")
public class AdminLoginServlet extends HttpServlet {
     private AdminService adminService = AdminServiceFactory.getAdminService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //测试
        // System.out.println("username = " + username);
        // System.out.println("password = " + password);

        boolean flag = adminService.adminLogin(username , password);

        if (flag){
            //将用户名和密码存到Cookie
            Cookie cookie = new Cookie("username" , username);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);

            cookie = new Cookie("password" , password);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);

            //帐号密码正确
            // response.sendRedirect("managerPage.jsp");
            request.getRequestDispatcher("managerPage.jsp").forward(request,response);
        }else {
            //帐号密码错误
            request.setAttribute("message" , "帐号密码错误");
            request.getRequestDispatcher("index.jsp").forward(request , response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
